import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import '../../utils/api.dart';
import '../../utils/tools.dart';
import '../../models/feedback_model.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  final FeedbackModel _model = FeedbackModel();
  bool hasChange = false;
  bool isSubmitting = false;

  Future<bool> doYouQuit() async {
    return (await MyDialog.confirm('留言还没提交，确定退出？')) ?? false;
  }

  submitFeedback() async {
    if (isSubmitting) return;
    if (_model.realName.isEmpty) {
      MyDialog.toast('请填写姓名', iconType: IconType.error);
      return;
    }
    if (!Tools.isMobile(_model.mobile)) {
      MyDialog.toast('请填写电话', iconType: IconType.error);
      return;
    }
    if (_model.content.length < 5) {
      MyDialog.toast('请填写留言内容', iconType: IconType.error);
      return;
    }
    setState(() {
      isSubmitting = true;
    });
    final result = await Api.post('common/do_feedback', _model.toJson());
    setState(() {
      isSubmitting = false;
    });
    if (result.code == 1) {
      MyDialog.toast('留言提交成功', iconType: IconType.success);
      Timer(const Duration(seconds: 1), () {
        Navigator.pop(context);
      });
    } else {
      MyDialog.alert(result.message);
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(
        title: const Text('留言'),
        actions: [
          TextButton(
            onPressed: submitFeedback,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                if (isSubmitting)
                  const Padding(
                    padding: EdgeInsets.only(right: 8),
                    child: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        color: Colors.white,
                        strokeWidth: 2,
                      ),
                    ),
                  ),
                Text(
                  '提交',
                  style: TextStyle(color: colorScheme.onPrimary, fontSize: 18),
                ),
                const SizedBox(width: 10),
              ],
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Hero(
            tag: 'feedback-page',
            child: SingleChildScrollView(
              child: Form(
                onChanged: () {
                  setState(() {
                    hasChange = true;
                  });
                },
                onWillPop: hasChange ? doYouQuit : null,
                autovalidateMode: AutovalidateMode.onUserInteraction,
                child: Column(
                  children: [
                    ListTile(
                      minLeadingWidth: 20,
                      leading: const Icon(Icons.person),
                      title: TextFormField(
                        onChanged: (String? val) {
                          _model.realName = val ?? '';
                        },
                        initialValue: _model.realName,
                        validator: (String? value) {
                          return (value != null && value.isNotEmpty)
                              ? null
                              : '请填写姓名';
                        },
                        decoration: const InputDecoration(
                          hintText: '真实姓名',
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    ListTile(
                      minLeadingWidth: 20,
                      leading: const Icon(Icons.phone),
                      title: TextFormField(
                        onChanged: (String? val) {
                          _model.mobile = val ?? '';
                        },
                        initialValue: _model.mobile,
                        validator: (String? value) {
                          return Tools.isMobile(value) ? null : '请填写手机号码';
                        },
                        decoration: const InputDecoration(
                          hintText: '联系电话',
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    ListTile(
                      minLeadingWidth: 20,
                      leading: const Icon(Icons.email),
                      title: TextFormField(
                        onChanged: (String? val) {
                          _model.email = val ?? '';
                        },
                        initialValue: _model.email,
                        validator: (String? value) {
                          return Tools.isEmail(value) ? null : '请填写邮箱地址';
                        },
                        decoration: const InputDecoration(
                          hintText: '联系邮箱',
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    ListTile(
                      title: Padding(
                        padding: const EdgeInsets.symmetric(vertical: 16.0),
                        child: TextFormField(
                          onChanged: (String? val) {
                            _model.content = val ?? '';
                          },
                          initialValue: _model.content,
                          validator: (String? value) {
                            return (value != null && value.length > 5)
                                ? null
                                : '请填写留言内容(5个字以上)';
                          },
                          maxLines: 5,
                          decoration: const InputDecoration(
                            labelText: '留言内容',
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            floatingLabelStyle: TextStyle(fontSize: 18),
                            border: OutlineInputBorder(),
                            hintText: '请填写留言内容(5个字以上)',
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: isSubmitting ? null : submitFeedback,
                      child: Padding(
                        padding: const EdgeInsets.symmetric(
                          vertical: 10,
                          horizontal: 50,
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            if (isSubmitting)
                              Padding(
                                padding: const EdgeInsets.only(right: 8),
                                child: SizedBox(
                                  width: 16,
                                  height: 16,
                                  child: CircularProgressIndicator(
                                    color: colorScheme.onPrimary,
                                    strokeWidth: 2,
                                  ),
                                ),
                              ),
                            Text(
                              '提交留言',
                              style: Theme.of(context)
                                  .textTheme
                                  .titleLarge!
                                  .copyWith(color: colorScheme.onPrimary),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
